package it.truestoryfactory.tsq.game.util;

import java.util.Collection;
import java.util.Iterator;

import android.net.wifi.p2p.WifiP2pDevice;
import android.util.Log;

public class TableMacIp {
	
	private static final int MAC_COLUMN = 0;
	private static final int IP_COLUMN = 1;
	private String[][] table = null;
	
	public TableMacIp(int numDevices) {
		table = new String [numDevices][2];
		Log.d(this.getClass().getName(), "new table created " + table.length + " x " + table[0].length);
	}
	
	public TableMacIp(Collection<WifiP2pDevice> deviceList) {
		table = new String [deviceList.size()][2];
		Log.d(this.getClass().getName(), "new table created " + table.length + " x " + table[0].length);
		Iterator<WifiP2pDevice> iterator = deviceList.iterator();
		WifiP2pDevice device = null;
		int i = 0;
		while (iterator.hasNext()){
			device = iterator.next();		
			setMac(i, device.deviceAddress);
			i++;
		}
	}

	private void setMac(int i, String deviceAddress) {
		table[i][MAC_COLUMN]=deviceAddress;
	}
	
	public boolean setIpByMac(String ip, String mac){
		for (int i=0; i<table.length; i++){
			if(table[i][MAC_COLUMN].equalsIgnoreCase(mac)){
				table[i][IP_COLUMN] = ip;
				return true;
			}
		}
		return false;
	}

	public void setIpAndMac(int index, String ip, String mac) throws ArrayIndexOutOfBoundsException{
		if (index < 0 || index >= table.length)
			throw new ArrayIndexOutOfBoundsException();
		table[index][MAC_COLUMN] = mac;
		table[index][IP_COLUMN] = ip;
	}

	public int getIndexByIp(String ip) {
		for(int i=0; i<table.length; i++){
			if(table[i][IP_COLUMN].equals(ip))
				return i;
		}
		return -1;
	}
	
	public String getIpByIndex(int index) {
		return table[index][IP_COLUMN];
	}
	
	public String getMacByIndex(int index) {
		return table[index][MAC_COLUMN];
	}
	
	public int getDevicesNumber() {
		return table.length;
	}
	
	public void printTable(){
		Log.d(this.getClass().getName(), "table is " + table.length + " x " + table[0].length);
		for(int i=0; i<table.length; i++)
			Log.d("TABLE MAC IP", i +": " + table[i][MAC_COLUMN] + "-->" + table[i][IP_COLUMN]);
	}

	public void setMacByIndex(int i, String mac) {
		table[i][MAC_COLUMN] = mac;
	}
	
	public void setIpByIndex(int i, String ip) {
		table[i][IP_COLUMN] = ip;
	}

}
